<template>
  <!-- 折线图5  -->
  <div ref="index" class="index"></div>
</template>
<script setup lang="ts">
import * as echarts from "echarts";
import { ref, watch, nextTick } from "vue";
// 接收值
let props = defineProps({
  carData: {
    type: Object,
    default: false,
  },
});
// 定义值
let index = ref(); //ref的应用
// 定义加载函数
let initCharts = () => {
  let chart = echarts.init(index.value);
  let N_POINT = 90; // 角度
  let YMAX = 10; // Y轴放大倍数

  //正弦
  let genSinItem = function (k) {
    return Math.sin((Math.PI / N_POINT) * 6 * k) * YMAX;
  };
  //方波
  let genSquItem = function (k) {
    if (k % 2 === 0) {
      return 30;
    } else {
      return 20;
    }
  };
  //三角波
  let genTriItem = function (k) {
    if (k % 2 === 0) {
      return 50;
    } else {
      return 40;
    }
  };
  let option = {
    backgroundColor: "#02234c",
    tooltip: {
      trigger: "axis",
      backgroundColor: "#07172c",
      textStyle: {
        color: "rgba(126,199,255,1)",
      },
      axisPointer: {
        type: "cross",
      },
    },
    grid: {
      top: "10%",
      left: "12%",
      right: "4%",
      bottom: "20%",
    },
    dataZoom: [
      {
        type: "inside",
        realtime: true,
      },
    ],
    xAxis: {
      type: "category",
      min: 0,
      max: N_POINT,
      axisLabel: {
        textStyle: {
          color: "#7ec7ff",
        },
      },
    },
    yAxis: {
      max: 50,
      min: -50,
      axisLabel: {
        textStyle: {
          color: "#7ec7ff",
        },
      },
    },
    series: [
      {
        name: "正弦",
        type: "line",
        data: Array.apply(null, Array(N_POINT)).map((item, i) => [
          i,
          genSinItem(i),
        ]),
        showSymbol: false,
      },
      {
        name: "方波",
        type: "line",
        step: "start",
        data: Array.apply(null, Array(N_POINT)).map((item, i) => genSquItem(i)),
        showSymbol: false,
      },
      {
        name: "三角波",
        type: "line",
        data: Array.apply(null, Array(N_POINT)).map((item, i) => genTriItem(i)),
        showSymbol: false,
      },
    ],
  };
  console.log("[option]", option);

  chart.setOption(option, true);
  // 当窗口大小改变时候，echarts重置大小
  window.addEventListener("resize", () => {
    chart.resize();
  });
};

// 监听当配置项发生变化的时候，调用加载函数
watch(
  () => props.carData,
  (val) => {
    if (Object.keys(val)) {
      nextTick(() => {
        initCharts();
      });
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="less">
.index {
  width: 100%;
  height: 200px;
}
</style>
